10. Exercise: Cancel the Notification

L1 A09 SC Cancel The Notificaiton

Android Developer Documentation

Exercise

  1. Open NotificationsUtil.kt



  2. Add an extension function on NotificationManager which calls cancelAll.
// NotificationUtils.kt

// TODO: Step 1.14 Cancel all notifications
/**
 * Cancels all notifications.
 *
 */
fun NotificationManager.cancelNotifications() {
    cancelAll()
}
  1. Now open EggTimerViewModel.kt and find the startTimer function.



  2. Get an instance of the NotificationManager from the system and call cancelNotifications() extension function.
       //TODO Step 1.15 call cancel notification
        val notificationManager =
           ContextCompat.getSystemService(
                app,
                NotificationManager::class.java
            ) as NotificationManager
        notificationManager.cancelNotifications()       
  1. Run the app and start the timer. After you see the notification, start the timer again and observe how our app automatically deleted the previous notification from the status bar.